//
//  NSArray+SafeMethod.m
//  IHome
//
//   Created by zhujizheng on 2020/2/18.
//  Copyright © 2019年 com.zhujizheng. All rights reserved.
//

#import "NSArray+SafeMethod.h"
#import <objc/runtime.h>
@implementation NSArray (SafeMethod)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self exchangeSelector:@selector(py_zeroObjectAtIndex:) forClass:objc_getClass("__NSArray0")];
        [self exchangeSelector:@selector(py_singleObjectAtIndex:) forClass:objc_getClass("__NSSingleObjectArrayI")];
        [self exchangeSelector:@selector(py_objectAtIndex:) forClass:objc_getClass("__NSArrayI")];
    });
}

+ (void)exchangeSelector:(SEL)selector forClass:(Class)class
{
    SEL originalSelector = @selector(objectAtIndex:);
    SEL swizzledSelector = selector;
    
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    
    BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    if (didAddMethod) {
        NSLog(@"didAddMethod");
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        NSLog(@"didnotAddMethod");
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

#pragma mark - 替换__NSArray0的objectAtIndex:方法
- (nullable id)py_zeroObjectAtIndex:(NSUInteger)index
{
    if (index < self.count) {
        return [self py_zeroObjectAtIndex:index];
    } else {
        NSLog(@"数组越界，数组长度大于1，%@", self);
        return nil;
    }
}

#pragma mark - 替换__NSSingleObjectArrayI的objectAtIndex:方法
- (nullable id)py_singleObjectAtIndex:(NSUInteger)index
{
    if (index < self.count) {
        return [self py_singleObjectAtIndex:index];
    } else {
        NSLog(@"数组越界，数组长度大于1，%@", self);
        return nil;
    }
}

#pragma mark - 替换__NSArrayI的objectAtIndex:方法
- (nullable id)py_objectAtIndex:(NSUInteger)index
{
    if (index < self.count) {
        return [self py_objectAtIndex:index];
    } else {
        NSLog(@"数组越界，数组长度大于1，%@", self);
        return nil;
    }
}

@end
